import jwt, { JwtPayload } from 'jsonwebtoken'
import { Unauthorized } from 'http-errors'
import { failure } from '../utils/responses'
import { Request, Response, NextFunction } from "express";

export interface AuthRequest extends Request {
  id: string // 用户表的主键id
}

export async function userAuth(req: Request, res: Response, next: NextFunction) {
  try {
    // 判断 Token 是否存在
    const token = req.headers.authorization as string
    if (!token) throw new Unauthorized('当前接口需要认证才能访问。')

    // 判断 Token 是否正确
    const decoded = jwt.verify(token, process.env.JWT_SECRET_KEY) as JwtPayload

    // 从 jwt 中，解析出之前存入的 id
    const { id } = decoded as JwtPayload

    // 如果通过验证，将userId挂载到req上，方便后续中间件或路由使用
    (req as AuthRequest).id = id

    // 一定要加 next()，才能继续进入到后续中间件或路由
    next()
  } catch (error) {
    failure(res, error)
  }
}
